<?php
/**
 * user.php
 * 
 * Created on 2014-10-17
 * Create by Calvin.Wang
 */

namespace haibao\cms\business;

use \haibao\cms\model\filter\User as UserFilter;
use haibao\cms\business\BusinessException;

class User extends \haibao\cms\business\Base{
	
	const USER_MAX_FROZEN_TIME = 2;
	
	public static function backPassword($userId,$code,$newPassword,$confirmPassword){
		if (!$userId){
			throw new BusinessException('用户Id不能为空');
		}
		if (!$code){
			throw new BusinessException('验证码不能为空');
		}
		if ($code != self::getBackPasswordCode($userId)){
			throw new BusinessException('验证码错误');
		}
		if (!$newPassword){
			throw new BusinessException('密码不能为空');
		}
		if ($newPassword != $confirmPassword){
			throw new BusinessException('两次密码不相同');
		}
		
		$data = new \haibao\cms\data\User();
		
		$data->backPassword($userId,$newPassword);
		$data->removeBackPasswordCode($userId);
	}
	
	public static function saveBackPasswordCode($userId,$code){
		$data = new \haibao\cms\data\User();
		$times = $data->getBackPasswordTimes($userId);
		if ($times >= 10){
			throw new BusinessException('今日找回密码的次数已达到10次！');
		}
		
		$data->saveBackPasswordCode($userId,$code);
		$data->saveBackPasswordTimes($userId,$times + 1);
	}
	
	public static function getBackPasswordCode($userId){
		if (!$userId){
			throw new BusinessException('用户Id不能为空');
		}
	
		$data = new \haibao\cms\data\User();
	
		return $data->getBackPasswordCode($userId);
	}
	
	/**
	 * 重设密码
	 * @param int $userId
	 */
	public static function resetPassword($userId){
		self::checkOperation(self::FUNC_CODE_USER_EDIT);
		
		if (!$userId){
			$userId = self::getCurrentUser()->Id;
		}
		
		$data = new \haibao\cms\data\User();
		$user = $data->getUserById($userId);
		$password = md5(111111);
		$data->updateById($userId, array('Password'=>$password,'Status'=>\haibao\cms\model\data\User::STATUS_FORCE_CHANGE_PASSWORD));
		
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, array('Id'=>$userId,'Passwrod'=>$password));
	}
	
	/**
	 * 设置用户状态
	 * @param int $status
	 * @param string $userId
	 */
	public static function setStatus($status,$userId = null){
		self::checkOperation(self::FUNC_CODE_USER_EDIT);
		
		if (!$userId){
			$userId = self::getCurrentUser()->Id;
		}		
		
		$data = new \haibao\cms\data\User();
		$data->updateStatus($userId, $status);
		
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, array('Id'=>$userId,'Status'=>$status));
	}
	
	/**
	 * 修改用户
	 * @param int $id
	 * @param array $arrSet
	 */
	public static function editUser($id,$arrSet){
		self::checkOperation(self::FUNC_CODE_USER_EDIT);
		
		$data = new \haibao\cms\data\User();
		if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL]) && empty($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL])){
			throw new BusinessException('办公邮箱不能为空',self::DATA_EMPTY_NAME);
		}
		/* if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_GROUPS]) && empty( $arrSet[UserFilter::CONDITION_FIELD_NAME_GROUPS])){
			throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
		} */
		if (isset($arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE]) && $arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE] == 0){
			$leader = $data->getOneById($arrSet[UserFilter::CONDITION_FIELD_NAME_LEADER_ID]);
			$arrSet[UserFilter::CONDITION_FIELD_NAME_JOB_TYPE] = $leader->JobType && $leader->JobType != 0 ? $leader->JobType : \haibao\cms\model\data\User::JOB_TYPE_OTHER;
		}
		if ( ($user = $data->getUserByEmail($arrSet[UserFilter::CONDITION_FIELD_NAME_EMAIL])) && $user->Id != $id){
			throw new BusinessException('办公邮箱已存在',self::DATA_ERROR_EMAIL_EXIST);
		}
		if(isset($arrSet[UserFilter::CONDITION_FIELD_NAME_USER_NAME])){
			unset($arrSet[UserFilter::CONDITION_FIELD_NAME_USER_NAME]);
		}
		if(isset($arrSet[UserFilter::CONDITION_FIELD_NAME_REAL_NAME])){
			unset($arrSet[UserFilter::CONDITION_FIELD_NAME_REAL_NAME]);
		}
		
		if(!isset($arrSet[\haibao\cms\model\filter\User::CONDITION_FIELD_NAME_GROUPS])){
			$data->removeUserGroups($id);
		}
		$data->updateById($id, $arrSet);
		
		$arrSet['Id'] = $id;
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, $arrSet);
	}
	
	public static function login($userName,$password,&$needCode,$code = ''){
		if (!$userName){
			throw new BusinessException('用户名不能为空',self::DATA_EMPTY_NAME);
		}
		if (!$password){
			throw new BusinessException('密码不能为空',self::DATA_EMPTY_PASSWORD);
		}
		
		$data = new \haibao\cms\data\User();
		$model = $data->getUserByName($userName);
		if(!$model){
	 		$model = $data->getUserByEmail($userName,false);
			if (!$model){
				$model = $data->getUserByMobile($userName,false);
				if(!$model){
					throw new BusinessException('用户不存在',self::DATA_ERROR_NAME);
				}
			}
		}
		
		if ($needCode){
			self::checkCaptcha($code);
		}
		
		$userCache = new \haibao\cms\cache\User();
		$time = $userCache->getkUserFrozenTime($userName);
		if($time){
			if($time >= self::USER_MAX_FROZEN_TIME) {
				$needCode = 1;
			}
		}else{
			$time = 0;
		}
		
		if ($model->Password != md5($password)){
			$userCache->setUserFrozenTime($userName,$time+1);
			throw new BusinessException('密码不正确',self::DATA_ERROR_PASSWORD);
		}
		if ($model->Status == \haibao\cms\model\data\User::STATUS_DIMISSION || 
			$model->Status == \haibao\cms\model\data\User::STATUS_FROZEN){
			throw new BusinessException('登录失败',self::DATA_ERROR);
		}

		// TODO : 获取当前登陆用户的下属用户Id
		$historyData = array(
			'userName' => $userName,
			'password' => $model->Password,
			'IP' => self::getIPaddress()
		);
		self::saveOperateHistory(\haibao\cms\business\Base::FUNC_CODE_USER_LOGIN, $historyData,$model->Id);
		$userCache->delUserFrozen($userName);
		return $model;
	}
	
	public static function checkCaptcha($captcha,$isReg = false){
		$captcha = strtolower( $captcha );
	
		$ret = true;
		if(mb_strlen($captcha) == 0){
			throw new BusinessException('请输入正确的验证码',self::DATA_ERROR_CAPTCHA);
		}
		$sessionId = \haibao\frame\http\Cookie::get('__cmscaptcha');
		$rightCaptcha = \haibao\comment\cache\CommentCache::getCrontabCache($sessionId);
		if($captcha != $rightCaptcha){
			throw new BusinessException('请输入正确的验证码',self::DATA_ERROR_CAPTCHA);
		}
		
		\haibao\comment\cache\CommentCache::delCrontabCache($sessionId);
			
		return $ret;
	}
	
	/**
	 * @param int $userId
	 * @return \haibao\cms\model\data\User
	 */
	public static function getUserById($userId){
		if (!$userId){
			throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
		}
		
		$data = new \haibao\cms\data\User();
		$model = $data->getUserById($userId);
		if (!$model){
			throw new BusinessException('用户不存在',self::DATA_ERROR_NAME);
		}
		
		return $model;
	}
	
	/**
	 * 设置用户组用户
	 * @param unknown_type $groupId
	 * @param unknown_type $userIds
	 */
	public static function setGroupUser($groupId,$userIds){
		if(empty($groupId)){
			throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
		}
		$data = new \haibao\cms\data\User();
		$data->setGroupUser($groupId, $userIds);
		self::saveOperateHistory(self::FUNC_CODE_USER_ADD, array('GroupId'=>$groupId,'UserIds'=>$userIds));
	}
	
	/**
	 * 添加用户
	 * @param \haibao\cms\model\data\User $model
	 */
	public static function addUser($model){
		self::checkOperation(self::FUNC_CODE_USER_ADD);
		$data = new \haibao\cms\data\User();
		/* if (!$model->UserName){
			throw new BusinessException('登录名不能为空',self::DATA_EMPTY_NAME);
		} */
		if (!$model->RealName){
			throw new BusinessException('姓名不能为空',self::DATA_EMPTY_REAL_NAME);
		}
		if (!$model->JobNum){
			throw new BusinessException('工号不能为空',self::DATA_EMPTY);
		}
		if (!$model->Email){
			throw new BusinessException('办公邮箱不能为空',self::DATA_EMPTY_NAME);
		}
		/* if (!$model->Groups){
			throw new BusinessException('用户所属组不能为空',self::DATA_EMPTY_USER_GROUP);
		} */
		if (!$model->JobType){
			$leader = $data->getOneById($model->LeaderId);
			$model->JobType = $leader->JobType ? $leader->JobType: \haibao\cms\model\data\User::JOB_TYPE_OTHER;
		}
		if ($data->getUserByName($model->UserName)){
			throw new BusinessException('用户名称已存在',self::DATA_ERROR_NAME_EXIST);
		}
		if ($data->getUserByEmail($model->Email)){
			throw new BusinessException('办公邮箱已存在',self::DATA_ERROR_EMAIL_EXIST);
		}
		if ($model->Mobile && $data->getUserByMobile($model->Mobile)){
			throw new BusinessException('手机号已存在',self::DATA_ERROR_EMAIL_EXIST);
		}
		
		$model->Password = md5(111111);
		$model->CreateTime = new \DateTime();
		$model->Status = \haibao\cms\model\data\User::STATUS_FORCE_CHANGE_PASSWORD;
		$model->CreateBy = self::getCurrentUser()->Id;
		
		$data->add($model);
		self::saveOperateHistory(self::FUNC_CODE_USER_ADD, $model->toArray(true,true));
	}
	
	/**
	 * 通过用户名称获取用户
	 * @param string $name
	 */
	public static function getUserByName($name){
		$data = new \haibao\cms\data\User();
		
		return $data->getUserByName($name);
	}
	/**
	 * 通过userIds获取用户名
	 * @param array $userIds
	 */
	public static function getUserNameByIds($userIds){
		$data = new \haibao\cms\data\User();
		if(!is_array($userIds)){
			$userIds = array($userIds);
		}
		return $data->getUserNameByIds($userIds);
	}
	
	/**
	 * 通过Email获取用户
	 * @param string $email
	 */
	public static function getUserByEmail($email){
		$data = new \haibao\cms\data\User();
		
		return $data->getUserByEmail($email);
	}
	
	public static function getUserByMobile($mobile){
		$data = new \haibao\cms\data\User();
		
		return $data->getUserByMobile($mobile);
	}

	public static function getUserByJobNum($jobNum){
		$data = new \haibao\cms\data\User();
	
		return $data->getUserByJobNum((int)$jobNum);
	}
	/**
	 * @param \haibao\cms\data\filter\User $filter
	 */
	public static function getAll($filter){
		$data = new \haibao\cms\data\User();
		
		return $data->getAll($filter);
	}
	
	/**
	 * @param \haibao\cms\data\filter\User $filter
	 */
	public static function checkUserPassword($password,$userId){
		if(!$password){
			throw new \haibao\cms\business\BusinessException("密码不能为空",self::DATA_EMPTY_PASSWORD);
		}
		if(!$userId){
			$userModel = self::getCurrentUser();
			$userId = $userModel->Id;
		}
		$data = self::getUserById($userId);
		$result = false;
		if($data && $data->Password == md5($password)){
			$result = true;
		}
		
		return $result;
	}

	public static function editpassword($origialPwd,$newPwd,$confirmNewPwd,$isForceEdit){
		if(!$isForceEdit && !$origialPwd){
			throw new \haibao\cms\business\BusinessException('原密码不能为空',self::DATA_EMPTY_PASSWORD);
		}
		if(!$isForceEdit && !self::checkUserPassword($origialPwd,null)){
			throw new \haibao\cms\business\BusinessException('原密码错误',self::DATA_ERROR_PASSWORD);
		}
		if(!$newPwd){
			throw new \haibao\cms\business\BusinessException('新密码不能为空',self::DATA_EMPTY_PASSWORD);
		}
		if(!$confirmNewPwd){
			throw new \haibao\cms\business\BusinessException('确认密码不能为空',self::DATA_EMPTY_PASSWORD);
		}
		if(!preg_match('/^[\da-zA-Z\!\_\@\#\$\%\^\&\*\?\.]{6,18}$/i', $newPwd)){
			throw new \haibao\cms\business\BusinessException('长度在6~18之间，只能包含字符、数字和下划线',self::DATA_ERROR_PASSWORD);
		}
		if($newPwd!==$confirmNewPwd){
			throw new \haibao\cms\business\BusinessException('两次密码不一致',self::DATA_ERROR);
		}
		
		$data = new \haibao\cms\data\User();
		$userModel = self::getCurrentUser();
		$userId = $userModel->Id;
		$history_changepwd = array();
		if ($isForceEdit){
			$data->updateById($userId, array('Password'=>md5($newPwd),'Status'=>\haibao\cms\model\data\User::STATUS_ENABLE));	
			$history_changepwd = array(
					'id' =>$userId ,
					'Password'=>md5($newPwd),
					'Status'=>\haibao\cms\model\data\User::STATUS_ENABLE
			);
		}
		else{
			$data->updateById($userId, array('Password'=>md5($newPwd)));
			$history_changepwd = array(
					'id' =>$userId ,
					'Password'=>md5($newPwd)
			);
		}
		
		self::saveOperateHistory(self::FUNC_CODE_USER_CHANGE_PASSWORD, $history_changepwd);
	}
	
	public static function editPenName($newPn){		
		$data = new \haibao\cms\data\User();
		$userModel = self::getCurrentUser();
		$userId = $userModel->Id;
		$history_changepwd = array();
		$data->updateById($userId, array('PenName'=>$newPn));	
		$history_changepwd = array(
				'id' =>$userId ,
				'PenName'=>$newPn,
				'Status'=>\haibao\cms\model\data\User::STATUS_ENABLE
		);
		
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, $history_changepwd);
	}
	
	/**
	 * 获取用户是否有操作权限(包括上下级和同级的权限)
	 * @param : Int $userId 用户Id
	 * @return : boolean
	 */
	public static function getIsCurrentPermissions($userId){
		
		$lowflag = $sameFlag = false;
		$userModel = self::getCurrentUser();
		if($userModel->Permission == \haibao\cms\model\data\User::PERMISSION_ADMIN){
			$lowflag = $sameFlag = true;
			
		}else{
			if(in_array($userId, $userModel->LowerUser)){
				$lowflag = true;
			}
			if(in_array($userId,$userModel->SameUser)){
				$sameFlag = true;
			}
		}
		return array($lowflag,$sameFlag);
	}	
	/**
	 * 检查用户是否有下属用户
	 * @param :int $userId 用户Id
	 * @return:boolean
	 */
	public static function checkHasSubUser($userId){
		
		if (!$userId){
			throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
		}
		$userNames = array();
		$data = new \haibao\cms\data\User();
		$subUserIds = $data->getLowerUserById($userId);
		if($subUserIds){
			$userNames = $data->getUserNameByIds($subUserIds);
			unset($userNames[$userId]);
		}
		return $userNames;
	}
	/**
	 * 转移用户下的下属员工
	 * @param :int $userId 用户Id
	 * @param:int $transferId 转移到用户Id
	 * @return:boolean
	 */
	public static function transferSubUserByLeaderId($userId,$transferId){
		if (!$userId || !$transferId){
			throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
		}
		if($userId == $transferId){
		    throw new BusinessException('转移用户与被转移用户相同，不可操作');
		}
		$data = new \haibao\cms\data\User();
		$data->transferSubUserByLeaderId($userId,$transferId);
		
		self::saveOperateHistory(self::FUNC_CODE_USER_EDIT, array('id'=>$userId,'transferId'=>$transferId));
	}
	
	public static function getIPaddress(){
		$ip='';
		if (isset($_SERVER)){
			if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
				$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
			} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
				$ip = $_SERVER["HTTP_CLIENT_IP"];
			} else {
				$ip = $_SERVER["REMOTE_ADDR"];
			}
		} else {
			if (getenv("HTTP_X_FORWARDED_FOR")){
				$ip = getenv("HTTP_X_FORWARDED_FOR");
			} else if (getenv("HTTP_CLIENT_IP")) {
				$ip = getenv("HTTP_CLIENT_IP");
			} else {
				$ip = getenv("REMOTE_ADDR");
			}
		}
		return $ip;
	}
	
	public static function getLowerUserById($userId){
		if (!$userId){
			throw new BusinessException('用户ID不能为空',self::DATA_EMPTY_ID);
		}
		$data = new \haibao\cms\data\User();
		return $data->getLowerUserById($userId,true);
	}
	
	public static function getOne($filter){
		$data = new \haibao\cms\data\User();
	
		return $data->getOne($filter);
	}
	
	public static function getUserByDingId($dingId){
	    $data = new \haibao\cms\data\User();
	    return $data->getUserByDingId($dingId);
	}
	
	public static function getUserInfoByIds($userIds){
	    $data = new \haibao\cms\data\User();
	    return $data->getUserInfoByIds($userIds);
	}
}
